package com.bootdo.market.controller;

import com.alibaba.fastjson.JSON;
import com.bootdo.common.utils.*;
import com.bootdo.market.common.HistoryTodayRedis;
import com.bootdo.market.dao.CommonDao;
import com.bootdo.market.domain.ProductArticleDO;
import com.bootdo.market.service.AacommonService;
import com.bootdo.market.service.ProductArticleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

/**
 * @author jinse
 * @email market@jinse.com
 * @date 2019-04-16 19:03:14
 */

@Controller
@RequestMapping("/market/productArticle")
public class ProductArticleController {
    @Autowired
    private ProductArticleService productArticleService;
    @Autowired
    private AacommonService aacommonService;
    @Autowired
    private HistoryTodayRedis historyTodayRedis;
    @Autowired
    private CommonDao commonDao;


    @GetMapping()
    @RequiresPermissions("market:productArticle:productArticle")
    String ProductArticle() {
        return "market/productArticle/productArticle";
    }

    @ResponseBody
    @GetMapping("/list")
    @RequiresPermissions("market:productArticle:productArticle")
    public PageUtils list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);
        List<ProductArticleDO> productArticleList = productArticleService.list(query);
        if (productArticleList.size() > 0) {
            productArticleList.forEach(item -> {
                if (item.getArticlecoverurl() != null && !"".equals(item.getArticlecoverurl())) {
                    item.setArticlecoverurl("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + item.getArticlecoverurl());
                }
            });
        }
        int total = productArticleService.count(query);
        PageUtils pageUtils = new PageUtils(productArticleList, total);
        return pageUtils;
    }

    @GetMapping("/add")
    @RequiresPermissions("market:productArticle:add")
    String add() {
        return "market/productArticle/add";
    }


    @RequestMapping(value = "/tagListByProductid", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public String tagListByProductid(HttpServletRequest request, Integer productid) {
        List<Map<String, Object>> sdklist = aacommonService.tagListByProductid(productid);
        return JSON.toJSONString(sdklist);
    }

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
        String path = request.getSession().getServletContext().getRealPath("/");
        try {
            if (null != file) {
                String filename = file.getOriginalFilename();
                if (!"".equals(filename.trim())) {
                    File newFile = new File(path, filename);
                    FileOutputStream os = new FileOutputStream(newFile);
                    os.write(file.getBytes());
                    os.close();
                    file.transferTo(newFile);
                    //上传到OSS
                    String uploadUrl = AliyunOSSUtil.uploadFile(newFile, OssConstant.OSS_ENDPOINT_HISTORY_TODAY, OssConstant.OSS_BUCKETNAME_HISTORY_TODAY, OssConstant.OSS_FILE_HOST_HISTORY_TODAY);
                    if (StringUtils.isNotBlank(uploadUrl)) {
                        return newFile.getName() + "#" + uploadUrl + "#" + "http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + uploadUrl;
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();

        }
        return null;
    }

    @GetMapping("/edit/{id}")
    @RequiresPermissions("market:productArticle:edit")
    String edit(@PathVariable("id") Integer id, Model model) {
        ProductArticleDO productArticle = productArticleService.get(id);
//        String fileUrl = null, fileName = null;
        if (productArticle.getArticlecoverurl() != null && !"".equals(productArticle.getArticlecoverurl())) {
           /* if (historyDayArticle.getCoverUrl().contains(OssConstant.OSS_FILE_HOST_HISTORY_TODAY)) {
                fileName = historyDayArticle.getCoverUrl().substring(OssConstant.OSS_FILE_HOST_HISTORY_TODAY.length() + 1);
                fileUrl = historyDayArticle.getCoverUrl();
            }*/
            productArticle.setArticlecoverurlhidden("http://" + OssConstant.OSS_FILE_HISTORY_DOMAIN_NAME + "/" + productArticle.getArticlecoverurl());
        }
        productArticle.setArticlecontenthidden(new String(productArticle.getArticlecontent()));
        model.addAttribute("productArticle", productArticle);
        return "market/productArticle/edit";
    }

    /**
     * 保存
     */
    @Transactional
    @ResponseBody
    @PostMapping("/save")
    @RequiresPermissions("market:productArticle:add")
    public R save(ProductArticleDO productArticle) {
/*
        String historyMonthDay = productArticle.getArticlehistorydate().replace("-", "").substring(4, 8);
*/
        String historyMonthDay = productArticle.getArticlehistorydate().substring(productArticle.getArticlehistorydate().indexOf("-"), productArticle.getArticlehistorydate().length()).replace("-", "");
        productArticle.setArticlehistorymonthday(historyMonthDay);
        productArticle.setArticlesort("");
        if (productArticleService.save(productArticle) > 0) {
            ProductArticleDO dto = productArticleService.findArticlesortById(productArticle.getId());
            productArticleService.update(dto);
            ProductArticleDO aaa = productArticleService.get(productArticle.getId());
            //todo 更新文章内容进入redis
            updateArticleDataIntoRedis(aaa);
            return R.ok();
        }
        return R.error();
    }

    /**
     * 修改
     */
    @ResponseBody
    @RequestMapping("/update")
    @RequiresPermissions("market:productArticle:edit")
    public R update(ProductArticleDO productArticle) {
        String historyMonthDay = productArticle.getArticlehistorydate().substring(productArticle.getArticlehistorydate().indexOf("-"), productArticle.getArticlehistorydate().length()).replace("-", "");
        productArticle.setArticlehistorymonthday(historyMonthDay);
        ProductArticleDO bbb = productArticleService.get(productArticle.getId());
        //todo 先删除之前zset里面的对应的频道的文章
        deleteArticleRedis(bbb);


        productArticleService.update(productArticle);
        ProductArticleDO dto = productArticleService.findArticlesortById(productArticle.getId());
        productArticle.setArticlesort(dto.getArticlesort());
        productArticleService.update(productArticle);
        ProductArticleDO aaa = productArticleService.get(productArticle.getId());
        //todo 更新文章内容进入redis
        updateArticleDataIntoRedis(aaa);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/remove")
    @ResponseBody
    @RequiresPermissions("market:productArticle:remove")
    public R remove(ProductArticleDO productArticle) {
        productArticleService.update(productArticle);
        ProductArticleDO aaa = productArticleService.get(productArticle.getId());

        //todo 更新文章内容进入redis
        updateArticleDataIntoRedis(aaa);
        return R.ok();
    }

    /**
     * 删除
     */
    @PostMapping("/batchRemove")
    @ResponseBody
    @RequiresPermissions("market:productArticle:batchRemove")
    public R remove(@RequestParam("ids[]") Integer[] ids) {
        productArticleService.batchRemove(ids);
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("/batchredis")
    @ResponseBody
    @RequiresPermissions("market:productArticle:batchredis")
    public R batchredis() {
        List<ProductArticleDO> list = commonDao.batchRedisGetAllArticle();
        if (list != null && list.size() > 0) {

            for (int i = 0; i < list.size(); i++) {
                ProductArticleDO productArticle = list.get(i);
                ProductArticleDO aaa = productArticleService.get(productArticle.getId());
                String historyMonthDay = aaa.getArticlehistorydate().substring(aaa.getArticlehistorydate().indexOf("-"), aaa.getArticlehistorydate().length()).replace("-", "");
                aaa.setArticlehistorymonthday(historyMonthDay);
                productArticleService.update(aaa);
                ProductArticleDO dto = productArticleService.findArticlesortById(aaa.getId());
                aaa.setArticlesort(dto.getArticlesort());
                productArticleService.update(aaa);
                ProductArticleDO bbbb = productArticleService.get(productArticle.getId());
                //todo 更新文章内容进入redis
                updateArticleDataIntoRedis(bbbb);
            }
        }
        return R.ok();
    }

    /**
     * 将文章信息更新进入redis
     */
    void updateArticleDataIntoRedis(ProductArticleDO aaa) {

        List<Integer> integerList = commonDao.listCatalogByTagid(aaa.getTagid());
        if (integerList != null && integerList.size() > 0) {
            integerList.stream().forEach(integer -> {
                aaa.setCatalogid(integer);
                if (aaa.getPublishstate() == 1 && aaa.getDeletestate() == 1) {
                    aaa.setArticlecontenthidden(new String(aaa.getArticlecontent()));
                    historyTodayRedis.saveProductArticleRedis(aaa);
                } else {
                    for (int i = 0; i < 5; i++) {
                        historyTodayRedis.deleteProductArticleRedis(aaa);
                    }
                }
            });
        }

    }

    /**
     * 删除redis的文章信息
     */
    void deleteArticleRedis(ProductArticleDO aaa) {
        List<Integer> integerList = commonDao.listCatalogByTagid(aaa.getTagid());
        if (integerList != null && integerList.size() > 0) {
            integerList.stream().forEach(integer -> {
                aaa.setCatalogid(integer);
                for (int i = 0; i < 5; i++) {
                    historyTodayRedis.deleteProductArticleRedis(aaa);
                }
            });
        }
    }
}
